<template>
  <div>
    <div class="link" @click="leadout">导出问卷到pdf/word>></div>
    <p class="guide_text">可以将编辑好的问卷内容导出到pdf/word。</p>
  </div>
</template>

<script>
import { GetAllQuestionInfoWithoutUid } from "../api";

import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import {saveAs} from 'file-saver'

export default {
  data() {
    return {
      questions: {},
      bigTitle:"",
      show:false,
    };
  },
  props: {
    qid: Number,
  },
  mounted() {

  },
  methods: {
    
    
    async leadout() {
    console.log(this.qid);
    const result = await GetAllQuestionInfoWithoutUid(this.qid);
    console.log(result);

    var expressions = require('angular-expressions');
    var assign = require("lodash/assign");
// define your filter functions here, for example, to be able to write {clientname | lower}
    expressions.filters.lower = function(input) {
    // This condition should be used to make sure that if your input is
    // undefined, your output will be undefined as well and will not
    // throw an error
    if(!input) return input;
    return input.toLowerCase();
    }
function angularParser(tag) {
    if (tag === '.') {
        return {
            get: function(s){ return s;}
        };
    }
    const expr = expressions.compile(
        tag.replace(/(’|‘)/g, "'").replace(/(“|”)/g, '"')
    );
    return {
        get: function(scope, context) {
            let obj = {};
            const scopeList = context.scopeList;
            const num = context.num;
            for (let i = 0, len = num + 1; i < len; i++) {
                obj = assign(obj, scopeList[i]);
            }
            return expr(scope, obj);
        }
    };
}

    this.questions=result.question_list
    this.bigTitle=result.questionnaire_title
    this.show=result.is_order
    var i=1;
    for(i=1;i<=this.questions.length;i++){
        this.questions[i-1].index=i;
    }
    console.log(this.questions)
    console.log('aaa')
    console.log(this.bigTitle)
    console.log('bbb')
    console.log(this.show)

    let that = this;
    // 读取并获得模板文件的二进制内容
    JSZipUtils.getBinaryContent("/example.docx", function(error, content) {
      // model.docx是模板。我们在导出的时候，会根据此模板来导出对应的数据
      // 抛出异常
      if (error) {
        throw error;
      }
 
      // 创建一个PizZip实例，内容为模板的内容
      let zip = new PizZip(content);
      // 创建并加载docxtemplater实例对象
      let doc = new Docxtemplater(zip, {parser:angularParser});
      // 设置模板变量的值
      doc.setData({
        title:that.bigTitle,
        questions:that.questions,
        isshow:that.show
        
      });
 
      try {
        // 用模板变量的值替换所有模板变量
        doc.render();
      } catch (error) {
        // 抛出异常
        let e = {
          message: error.message,
          name: error.name,
          stack: error.stack,
          properties: error.properties
        };
        console.log(JSON.stringify({ error: e }));
        throw error;
      }
 
      // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
      let out = doc.getZip().generate({
        type: "blob",
        mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      });
      // 将目标文件对象保存为目标类型的文件，并命名
      saveAs(out, "问卷.docx");
    });

    }
  },
};
</script>
<style>
.link {
  margin-top: 50px;
  color: -webkit-link;
  text-decoration: underline;
}
.link:hover {
  cursor: pointer;
}
</style>